package ink.xiaobaibai.controller.buy;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ink.xiaobaibai.annotation.InsidePublicResources;
import ink.xiaobaibai.autoConfig.roleResources.ResourcesRoleMapping;
import ink.xiaobaibai.common.MyRole;
import ink.xiaobaibai.common.PageInfo;
import ink.xiaobaibai.common.RoleEvents;
import ink.xiaobaibai.common.SelectBuyBo;
import ink.xiaobaibai.entity.BuyOxygenDevice;
import ink.xiaobaibai.entity.BuyOzoneDevice;
import ink.xiaobaibai.response.ResponseFormat;
import ink.xiaobaibai.service.IAdminUserService;
import ink.xiaobaibai.service.IBuyOxygenDeviceService;
import ink.xiaobaibai.service.IBuyOzoneDeviceService;
import ink.xiaobaibai.units.MySecurity;
import ink.xiaobaibai.valited.UpdateGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

/**
 * @description: 购买业务臭氧控制层
 * @author: 小白白
 * @create: 2021-06-12
 **/

@CrossOrigin
@RequestMapping("/buy/ozone")
@RestController
@Api(tags = "购买业务臭氧控制层")
@Slf4j
@InsidePublicResources
public class BuyOzoneDeviceController {

    @Autowired
    private IBuyOzoneDeviceService buyOzoneDeviceService;

    @Autowired
    private IBuyOxygenDeviceService buyOxygenDeviceService;

    @Autowired
    private IAdminUserService adminUserService;

    /**
     * 查询臭氧机器
     */
    @PostMapping("/list")
    @ApiOperation("查询臭氧机器")
    public ResponseFormat getOzoneDeviceList(@RequestBody @Validated SelectBuyBo selectBuyBo) {
        Integer userId = MySecurity.getUserId();
        Set<String> roles = MySecurity.getRoles();
        if (!roles.contains(MyRole.POWER_BUY)) {
            RoleEvents roleEvents = new RoleEvents(MySecurity.getRole());
            roleEvents
                    .distributor(() -> selectBuyBo.setAdminUserId(userId))
                    .agent(() -> selectBuyBo.setDepId(this.adminUserService.getDepId(userId)))
                    .admin(() -> {
                    })
                    .execute();
        }
        PageInfo<BuyOzoneDevice> pageInfo = this.buyOzoneDeviceService.getList(selectBuyBo);
        return ResponseFormat.success(pageInfo);
    }

    /**
     * 增加臭氧机器
     */
    @PostMapping("/add")
    @ApiOperation("增加臭氧机")
    @ResourcesRoleMapping(resourceName = "增加购买臭氧机器", includeRoleNames = {MyRole.ADMIN, MyRole.POWER_BUY})
    public ResponseFormat addOzoneDevice(@RequestBody @Validated BuyOzoneDevice buyOzoneDevice) {
        //当前机器码是否重复
        String deviceCode = buyOzoneDevice.getDeviceCode();
        if (!this.buyOzoneDeviceService.okCode(deviceCode)) {
            return ResponseFormat.fail("当前机器码重复");
        }
        //对应氧气机是否存在 对应氧气机不是自己的机器
        QueryWrapper<BuyOxygenDevice> q1 = new QueryWrapper<>();
        q1.select("admin_user_id");
        q1.eq("id", buyOzoneDevice.getOxygenId());
        BuyOxygenDevice oxygenDevice = this.buyOxygenDeviceService.getOne(q1);
        if (oxygenDevice == null) {
            return ResponseFormat.fail("对应氧气机不存在");
        }
        Integer userId = MySecurity.getUserId();
        if (buyOzoneDevice.getAdminUserId() == null) {
            buyOzoneDevice.setAdminUserId(userId);
            buyOzoneDevice.setDepId(this.adminUserService.getDepId(userId));
        } else {
            if (!this.adminUserService.existsUser(buyOzoneDevice.getAdminUserId())) {
                return ResponseFormat.fail("绑定用户不存在");
            }
            buyOzoneDevice.setDepId(this.adminUserService.getDepId(buyOzoneDevice.getAdminUserId()));
        }
        this.buyOzoneDeviceService.save(buyOzoneDevice);
        return ResponseFormat.success();
    }

    /**
     * 给臭氧机绑定对应氧气机时,请求校验
     */
    @GetMapping("/valid-oxygen/{id}")
    @ApiOperation("为臭氧机绑定氧气机时,给出氧气机id的信息(用于提示)")
    public ResponseFormat validOxygen(@PathVariable("id") Integer deviceId) {
        BuyOxygenDevice buyOxygenDevice = this.buyOxygenDeviceService.getById(deviceId);
        if (buyOxygenDevice == null) {
            return ResponseFormat.fail("对应氧气机不存在");
        }
        if (buyOxygenDevice.getClientUserId() != null) {
            return ResponseFormat.fail("提示当前氧气机已经绑定了用户:" + buyOxygenDevice.getClientUserId() + ",请确保为当前订单购买用户");
        }
        return ResponseFormat.success();
    }


    /**
     * 删除臭氧机器 (只可删除未绑定的,防止卖出后删除)
     */
    @DeleteMapping("/delete/lower/{id}")
    @ApiOperation("删除臭氧机器,只可删除未绑定的客户的机器")
    @ResourcesRoleMapping(resourceName = "删除购买臭氧机器", includeRoleNames = {MyRole.ADMIN, MyRole.POWER_BUY})
    public ResponseFormat deleteDeviceByLower(@PathVariable("id") Integer id) {
        QueryWrapper<BuyOzoneDevice> q1 = new QueryWrapper<>();
        q1.select("admin_user_id", "client_user_id");
        q1.eq("id", id);
        BuyOzoneDevice buyOzoneDevice = this.buyOzoneDeviceService.getOne(q1);
        if (buyOzoneDevice.getClientUserId() != null) {
            return ResponseFormat.fail("当前机器已绑定客户,不可删除");
        }
        this.buyOzoneDeviceService.removeById(id);
        return ResponseFormat.success();
    }

    /**
     * 修改臭氧机器
     */
    @PutMapping("/update")
    @ApiOperation("修改臭氧机")
    @ResourcesRoleMapping(resourceName = "修改购买臭氧机器", includeRoleNames = {MyRole.ADMIN, MyRole.POWER_BUY})
    public ResponseFormat updateOzoneDevice(@RequestBody @Validated(value = UpdateGroup.class) BuyOzoneDevice buyOzoneDevice) {
        Integer userId = MySecurity.getUserId();
        QueryWrapper<BuyOzoneDevice> q0 = new QueryWrapper<>();
        q0.select("device_code", "client_user_id", "admin_user_id");
        q0.eq("id", buyOzoneDevice.getId());
        BuyOzoneDevice ozoneDevice = this.buyOzoneDeviceService.getOne(q0);
        if (buyOzoneDevice.getAdminUserId() != null && !StringUtils.equals(String.valueOf(buyOzoneDevice.getAdminUserId()), String.valueOf(ozoneDevice.getAdminUserId()))) {
            if (!this.adminUserService.existsUser(buyOzoneDevice.getAdminUserId())) {
                return ResponseFormat.fail("绑定用户不存在");
            }
            buyOzoneDevice.setDepId(this.adminUserService.getDepId(buyOzoneDevice.getAdminUserId()));
            buyOzoneDevice.setAdminUserId(buyOzoneDevice.getAdminUserId());
        }
        buyOzoneDevice.setType(buyOzoneDevice.getType());
        QueryWrapper<BuyOxygenDevice> q1 = new QueryWrapper<>();
        q1.eq("id", buyOzoneDevice.getOxygenId());
        q1.select("admin_user_id");
        BuyOxygenDevice oxygenDevice = this.buyOxygenDeviceService.getOne(q1);
        if (oxygenDevice == null) {
            return ResponseFormat.fail("对应氧气机不存在");
        }
        if (!ozoneDevice.getDeviceCode().equals(buyOzoneDevice.getDeviceCode())) {
            //机器码被修改了,验证新的是否重复
            QueryWrapper<BuyOzoneDevice> q2 = new QueryWrapper<>();
            q2.eq("device_code", buyOzoneDevice.getDeviceCode());
            if (this.buyOzoneDeviceService.count(q2) >= 1) {
                return ResponseFormat.fail("当前机器码重复");
            }
        }
        if (ozoneDevice.getClientUserId() != null && buyOzoneDevice.getClientUserId() != null && !ozoneDevice.getClientUserId().equals(buyOzoneDevice.getClientUserId())) {
            log.error("敏感操作:{}将机器{}的客户id改为{},原{}", userId, buyOzoneDevice.getId(), buyOzoneDevice.getClientUserId(), ozoneDevice.getClientUserId());
        }
        this.buyOzoneDeviceService.updateById(buyOzoneDevice);
        return ResponseFormat.success();
    }


}
